﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Routing;

namespace Simple.Services.Components
{
    /// <summary>
    /// 全局路由前缀配置
    /// </summary>
    public class RouteConventio : IApplicationModelConvention
    {
        /// <summary>
        /// 定义一个路由前缀变量
        /// </summary>
        private readonly AttributeRouteModel _centralPrefix;

        /// <summary>
        /// 调用时传入指定的路由前缀
        /// </summary>
        /// <param name="routeTemplateProvide"></param>
        public RouteConventio(IRouteTemplateProvider routeTemplateProvide)
        {
            _centralPrefix = new AttributeRouteModel(routeTemplateProvide);
        }

        /// <summary>
        /// 接口的Apply方法，在这个方法中根据情况来添加api 路由前缀
        /// </summary>
        /// <param name="application"></param>

        public void Apply(Microsoft.AspNetCore.Mvc.ApplicationModels.ApplicationModel application)
        {
            //遍历所有的Controller
            foreach (var controllers in application.Controllers)
            {
                //1、已经标记RouteAttribute 的 Controller
                //如果在控制器中已经标注有路由了，则会在路由的前面再添加指定的路由内容
                var matchedSelectors = controllers.Selectors.Where(x => x.AttributeRouteModel != null).ToList();
                if (matchedSelectors.Any())
                {
                    foreach (var selectorModel in matchedSelectors)
                    {
                        //在当前路由上再添加一个路由前缀
                        selectorModel.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_centralPrefix, selectorModel.AttributeRouteModel);
                    }
                }

                //2、没有标记RouteAttribute 的 Controller
                var unmatchedSelectors = controllers.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
                if (unmatchedSelectors.Any())
                {
                    foreach (var selectorModel in unmatchedSelectors)
                    {
                        // 添加一个 路由前缀
                        selectorModel.AttributeRouteModel = _centralPrefix;
                    }
                }
            }
        }
    }
}
